/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.devicetype.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.devicetype.param.*;
import vip.xiaonuo.biz.modular.org.entity.BizOrg;
import vip.xiaonuo.biz.modular.org.service.BizOrgService;
import vip.xiaonuo.common.enums.CommonRoleEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.devicetype.entity.DeviceType;
import vip.xiaonuo.biz.modular.devicetype.mapper.DeviceTypeMapper;
import vip.xiaonuo.biz.modular.devicetype.service.DeviceTypeService;

import javax.security.auth.login.LoginContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设备类型Service接口实现类
 *
 * @author Blurryface
 * @date  2025/07/06 15:03
 **/
@Service
public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceType> implements DeviceTypeService {
    @Resource BizOrgService bizOrgService;

    @Override
    public Page<DeviceType> page(DeviceTypePageParam deviceTypePageParam) {
        QueryWrapper<DeviceType> queryWrapper = new QueryWrapper<DeviceType>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(deviceTypePageParam.getOrgId())) {
            queryWrapper.lambda().like(DeviceType::getOrgId, deviceTypePageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(deviceTypePageParam.getTypeId())) {
            queryWrapper.lambda().like(DeviceType::getId, deviceTypePageParam.getTypeId());
        }
        if(ObjectUtil.isNotEmpty(deviceTypePageParam.getName())) {
            queryWrapper.lambda().like(DeviceType::getName, deviceTypePageParam.getName());
        }
        if(ObjectUtil.isAllNotEmpty(deviceTypePageParam.getSortField(), deviceTypePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(deviceTypePageParam.getSortOrder());
            queryWrapper.orderBy(true, deviceTypePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(deviceTypePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(DeviceType::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DeviceTypeAddParam deviceTypeAddParam) {
        DeviceType deviceType = BeanUtil.toBean(deviceTypeAddParam, DeviceType.class);
        this.save(deviceType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DeviceTypeEditParam deviceTypeEditParam) {
        DeviceType deviceType = this.queryEntity(deviceTypeEditParam.getId());
        BeanUtil.copyProperties(deviceTypeEditParam, deviceType);
        this.updateById(deviceType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DeviceTypeIdParam> deviceTypeIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(deviceTypeIdParamList, DeviceTypeIdParam::getId));
    }

    @Override
    public DeviceType detail(DeviceTypeIdParam deviceTypeIdParam) {
        return this.queryEntity(deviceTypeIdParam.getId());
    }

    @Override
    public DeviceType queryEntity(String id) {
        DeviceType deviceType = this.getById(id);
        if(ObjectUtil.isEmpty(deviceType)) {
            throw new CommonException("设备类型不存在，id值为：{}", id);
        }
        return deviceType;
    }

    @Override
    public List<DeviceTypeTreeParam> getAll(){
        QueryWrapper<DeviceType> queryWrapper = new QueryWrapper<DeviceType>();
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();

        // 超管和业管可以获取所有的机构
        if (!loginUser.getRoleCodeList().contains(CommonRoleEnum.SUPER_ADMIN.getEn_name()) && !loginUser.getRoleCodeList().contains(CommonRoleEnum.BIZ_ADMIN.getEn_name())) {
            queryWrapper.lambda().eq(DeviceType::getOrgId, loginUser.getOrgId());
        }
        queryWrapper.lambda().orderByAsc(DeviceType::getSortCode);
        List<DeviceType> deviceTypes = this.list(queryWrapper);

        // 构造树
        Map<String, List<DeviceType>> orgDeviceMap = deviceTypes
                .stream()
                .collect(Collectors.groupingBy(DeviceType::getOrgId));

        List<DeviceTypeTreeParam> res = new ArrayList<>();
        for (Map.Entry<String, List<DeviceType>> entry : orgDeviceMap.entrySet()) {
            String orgId = entry.getKey();
            List<DeviceType> devices = entry.getValue();

            // 创建机构节点
            DeviceTypeTreeParam orgNode = new DeviceTypeTreeParam();
            orgNode.setId(orgId);

            // 根据orgId去BizOrg中换取机构名称
            String orgName = bizOrgService.getById(orgId).getName();
            orgNode.setName(orgName);
            orgNode.setIsOrg(true);

            // 创建设备子节点
            List<DeviceTypeTreeParam> children = devices.stream().map(device -> {
                DeviceTypeTreeParam deviceNode = new DeviceTypeTreeParam();
                deviceNode.setId(device.getId());
                deviceNode.setName(device.getName());
                deviceNode.setIsOrg(false);
                return deviceNode;
            }).collect(Collectors.toList());

            orgNode.setChildren(children);
            res.add(orgNode);
        }
        return res;
    }

}
